package zt.bank.boot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import zt.bank.boot.pojo.Card;
import zt.bank.boot.pojo.Customer;
import zt.bank.boot.service.CardService;
import zt.bank.boot.service.CustomerService;
import zt.bank.boot.service.ProvService;

import java.io.IOException;

/**
 * @Author 宋伟宁
 * @Date 2023/11/9
 * @Version 1.0
 **/
@Controller
@RequestMapping("/customer")
public class CustomerController {

    @Resource
    private ProvService provService;
    @Resource
    private CustomerService customerService;
    @GetMapping("/")
    public String index(){
        return "index";
    }

    @Resource
    private CardService cardService;
    @GetMapping("/register")
    public String to_register(Model model){
        //获取省份
        model.addAttribute("ps",this.provService.list());
        return "register";
    }

    @PostMapping("/register")
    public String register(Customer customer, MultipartFile file, int pid, int cid, int aid, HttpSession session) throws IOException {
        // 客户信息插入到表中，并且获取id
        // 获取地址：省、市、区
        //图片的保存
        String path=System.getProperty("user.dir")+"\\src\\main\\resources\\static\\upload\\";
        //
        String uuid = UUID.fastUUID().toString().replace("-","")+file.getOriginalFilename();
        //保存图片
        FileUtil.writeBytes(file.getBytes(),path+uuid);
        customer.setPic(uuid);
         String card=this.customerService.register(customer,pid,cid,aid);
         //保存到session中（可以保存到model中）
         session.setAttribute("card",card);
        return "open_card";
    }

    @PostMapping("/open")
    public String open(Card card){
        UpdateWrapper<Card> wrapper =new UpdateWrapper<>();
        wrapper.set("balance",card.getBalance())
                .set("password",card.getPassword())
                .eq("cardnum",card.getCardnum());
        this.cardService.update(wrapper);
        return "redirect:/";
    }
}
